import { useQuery } from '@umijs/max';
// 公共函数
import '@/utils/adapter.min.js';
import { addCommas } from '@/utils/index';
import { WebRtcStreamer } from '@/utils/webRtcStreamer';
// 组件
// import CustomDatePicker from '@/components/CustomDatePicker';
// import DPlayerComponent from '@/components/DPlayerComponent';
import { MenuList } from '@/components/MenuList/menuList';
// import RTSPToHLSPlayer from '@/components/RTSPToHLSPlayer';
// 公共图表组件
import { BarChartBaseValue } from '@/components/Echarts/BarChartBaseValue';
import { BarChartTopFive } from '@/components/Echarts/BarChartTopFive';
import { LineChartBaseValue } from '@/components/Echarts/LineChartBaseValue';
import { PieChartProportion } from '@/components/Echarts/PieChartProportion';
// 图表组件
import { LineChart } from './components/lineChart'; // 折线 双轴坐标
// 图片
// import videoUrl from '@/assets/video/video.mp4';
// 接口地址
import { ApiUrlTwo } from '@/services/data-board/boardTwo';
// 接口
import { getIpList } from '@/services/data-board/boardOne';
import {
  getColdTemperatureMonitor,
  getFishTypeProportionOut,
  getPackingMonitor,
  getStockTotal,
  inStockTrend,
  outStockTrend,
  outTotalTop5,
  stockTrend,
} from '@/services/data-board/boardTwo';
// import { useEffect } from 'react';
// ts
import type {
  LineMonitorType,
  TopFiveType,
  TrendType,
  proporDataType,
} from '@/components/Echarts/typing';
import type { GetRawMaterialFishTopFiveType } from '@/services/data-board/typing';
import type { OutInStockBarType, StockType } from './typing';

// const dateTypes = [
//   {
//     name: '本月',
//     active: true,
//   },
//   {
//     name: '本季',
//     active: false,
//   },
//   {
//     name: '本年',
//     active: false,
//   },
// ];

let webRtcServer = null;

export default function DataBoardTwo() {
  // 获取视频ip地址
  const { data: ipData, isSuccess: ipIsSuccess } = useQuery({
    queryKey: ['getIpList'],
    queryFn: () => getIpList({ type: 2 }),
    refetchInterval: false,
  });
  console.log('ipIsSuccess', ipIsSuccess);
  if (ipIsSuccess) {
    const { resultData } = ipData;
    const ipAddress = resultData[0].ipAddress;
    console.log('ipAddress', ipAddress);
    const IpPath = process.env.VIDEO_URL ? process.env.VIDEO_URL : '';
    webRtcServer = new WebRtcStreamer('video1', IpPath);
    // webRtcServer.connect('rtsp://admin:zhuhai12@192.168.1.107', '', '', '');
    webRtcServer.connect(`rtsp://admin:zhuhai12@${ipAddress}`, '', '', '');
  }

  // 图1 数据
  let stockTrendBarData: TrendType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图1 库存数量趋势
  const { data: stockTrendData, isSuccess: stockTrendIsSuccess } = useQuery({
    queryKey: [ApiUrlTwo.STOCKTREND],
    queryFn: () => stockTrend({}),
  });

  if (stockTrendIsSuccess) {
    const { resultData } = stockTrendData;
    stockTrendBarData = {
      xAxisData: resultData[0].value.map((item) => item.time) ?? [],
      seriesData: [
        [], // 未返回基准值，要不要？
        resultData[0].value.map((item) => item.value) ?? [],
      ],
    };
  }

  // 图2 数据
  let outInStockBarData: OutInStockBarType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图2-1 出库数量趋势
  const { data: outStockTrendData, isSuccess: outStockTrendIsSuccess } =
    useQuery({
      queryKey: [ApiUrlTwo.OUTSTOCKTREND],
      queryFn: () => outStockTrend({}),
    });

  if (outStockTrendIsSuccess) {
    const { resultData } = outStockTrendData;
    outInStockBarData = {
      xAxisData: resultData[0].value.map((item) => item.time) ?? [],
      seriesData: [resultData[0].value.map((item) => item.value)],
    };
  }
  // 图2-2 入库数量趋势
  const { data: inStockTrendData, isSuccess: inStockTrendIsSuccess } = useQuery(
    {
      queryKey: [ApiUrlTwo.INSTOCKTREND],
      queryFn: () => inStockTrend({}),
    },
  );

  if (inStockTrendIsSuccess) {
    const { resultData } = inStockTrendData;
    outInStockBarData.seriesData.push(
      resultData[0].value.map((item) => item.value),
    );
  }

  // 图3 数据
  let packingBarData: LineMonitorType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图3 生产数据监控(表同冷库温度监控)
  const { data: packingData, isSuccess: packingIsSuccess } = useQuery({
    queryKey: [ApiUrlTwo.GETPACKINGMONITOR],
    queryFn: () => getPackingMonitor({}),
  });

  if (packingIsSuccess) {
    const { resultData } = packingData;
    packingBarData = {
      xAxisData: resultData[0].value.map((item) => item.time) ?? [],
      seriesData: resultData.map((el) => ({
        name: el.name,
        data: el.value.map((item) => item.value),
      })),
    };
  }

  // 图4 数据
  let fishTypeBarData: proporDataType.StateType = {
    seriesData: [],
  };
  // 图4 累计出库占比
  const { data: fishTypeData, isSuccess: fishTypeIsSuccess } = useQuery({
    queryKey: [ApiUrlTwo.GETFISHTYPEPROPORTIONOUT],
    queryFn: () => getFishTypeProportionOut({}),
  });

  if (fishTypeIsSuccess) {
    const { resultData } = fishTypeData;
    fishTypeBarData = {
      seriesData: resultData[0].data,
    };
  }

  // 图5 数据
  let outTotalBarData: TopFiveType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图5 出库数量top5
  const { data: outTotalData, isSuccess: outTotalIsSuccess } = useQuery({
    queryKey: [ApiUrlTwo.OUTTOTALTOP5],
    queryFn: () => outTotalTop5({}),
  });

  if (outTotalIsSuccess) {
    const { resultData } = outTotalData;
    let newResultData: GetRawMaterialFishTopFiveType.Value[] = [];
    resultData.forEach((el) => {
      newResultData.push({
        name: el.name,
        value: el.value.reduce((total, curr) => total + +curr.value, 0),
      });
    });
    // 辅助背景值
    const fData: number[] = [];
    const maxVal = newResultData.reduce((total, cur) => total + +cur.value, 0);
    newResultData.forEach(() => {
      fData.push(maxVal);
    });
    outTotalBarData = {
      xAxisData:
        newResultData
          .map((item, index) => `TOP${index + 1} ${item.name}`)
          .reverse() ?? [],
      seriesData: [
        newResultData.map((el) => el.value).reverse(),
        fData.reverse(),
      ],
    };
  }

  // 图6 数据
  let coldTemperatureBarData: LineMonitorType.StateType = {
    xAxisData: [],
    seriesData: [],
  };
  // 图6 冷库温度监控
  const { data: coldTemperatureData, isSuccess: coldTemperatureIsSuccess } =
    useQuery({
      queryKey: [ApiUrlTwo.GETCOLDTEMPERATUREMONITOR],
      queryFn: () => getColdTemperatureMonitor({}),
    });

  if (coldTemperatureIsSuccess) {
    const { resultData } = coldTemperatureData;
    coldTemperatureBarData = {
      xAxisData: resultData[0].value.map((item) => item.time) ?? [],
      seriesData: resultData.map((el) => ({
        name: el.name,
        data: el.value.map((item) => item.value),
      })),
    };
  }

  // 库存信息
  const { data: stockTotalData, isSuccess: stockTotalIsSuccess } = useQuery({
    queryKey: [ApiUrlTwo.GETSTOCKTOTAL],
    queryFn: () => getStockTotal({}),
  });
  let stockData = stockTotalData?.resultData as StockType.data[];
  // 产品品类占比
  let stockDataProp: StockType.data[] = [];
  if (stockTotalIsSuccess) {
    console.log('stockData', stockData);
    stockData.forEach((el, index) => {
      if (index != 2) {
        stockDataProp.push({
          name: el.name + '占比',
          value: +((el.value / stockData[2].value) * 100).toFixed(2),
        });
      }
    });
  }

  return (
    <div className="main-wrapper">
      {/* ---------- 左 ---------- */}
      <div className="main main-left">
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">库存数量趋势</div>
            {/* <CustomDatePicker picker="month"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <BarChartBaseValue trendData={stockTrendBarData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">出库/入库数量趋势</div>
            {/* <CustomDatePicker picker="month"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <LineChart outInStockBarData={outInStockBarData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">生产数据监控</div>
            {/* <CustomDatePicker picker="month"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <LineChartBaseValue monitorData={packingBarData} />
          </div>
        </div>
      </div>
      {/* ---------- 中 ---------- */}
      <div className="main main-center">
        {/* 视频 */}
        <div className="main-center-video2">
          {/* <DPlayerComponent url={videoUrl} /> */}
          {/* <RTSPToHLSPlayer hlsUrl={videoUrl} /> */}
          <video
            muted
            autoPlay
            id="video1"
            style={{ width: '100%', height: '100%', objectFit: 'fill' }}
          >
            您的浏览器不支持 video 标签。
          </video>
        </div>
        {/* 菜单 */}
        <div className="main-center-menu">
          {/* 对齐问题，所以写了两遍～ */}
          {stockTotalIsSuccess ? (
            <MenuList
              list={[
                {
                  name: stockData[2].name,
                  num: addCommas(stockData[2].value),
                  unit: '千克',
                },
                {
                  name: stockData[1].name,
                  num: addCommas(stockData[1].value),
                  unit: '千克',
                },
                {
                  name: stockData[0].name,
                  num: addCommas(stockData[0].value),
                  unit: '千克',
                },
              ]}
            />
          ) : null}
          {stockTotalIsSuccess ? (
            <MenuList
              list={[
                {
                  name: stockDataProp[1].name,
                  num: stockDataProp[1].value,
                  unit: '%',
                },
                {
                  name: stockDataProp[0].name,
                  num: stockDataProp[0].value,
                  unit: '%',
                },
                {},
              ]}
            />
          ) : null}
        </div>
      </div>
      {/* ---------- 右 ---------- */}
      <div className="main main-right">
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">累计出库占比</div>
            {/* <CustomDatePicker picker="month"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <PieChartProportion proporData={fishTypeBarData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">出库数量TOP5</div>
            {/* <div className="header-font header-font-type">
              {dateTypes.map((item) => (
                <span className="type" key={item.name}>
                  {item.name}
                </span>
              ))}
            </div> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <BarChartTopFive TopFiveData={outTotalBarData} />
          </div>
        </div>
        {/* box */}
        <div className="main-box">
          <div className="main-box-header">
            <div className="header-font">冷库温度监控</div>
            {/* <CustomDatePicker picker="date"></CustomDatePicker> */}
          </div>
          <div className="main-box-contain">
            {/* chart */}
            <LineChartBaseValue monitorData={coldTemperatureBarData} />
          </div>
        </div>
      </div>
    </div>
  );
}
